package com.example.aircraftwar.scorelist;

import android.content.Context;
import android.util.Log;

import com.example.aircraftwar.application.MainActivity;
import com.example.aircraftwar.startgame.StartGameActivity;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Stream;

public class ScoreDaoImpl implements ScoreDao{

    public static List<Score> scores;
    private Path path;
    private String filename;
    private Context context;

    public ScoreDaoImpl(Context context) throws IOException {
        this.context = context;
        if (StartGameActivity.selectPattern == 1) {
            path = Paths.get(context.getFilesDir().toString() + "/easyscorelist.txt");
            filename = "easyscorelist.txt";
        } else if (StartGameActivity.selectPattern == 2) {
            path = Paths.get(context.getFilesDir().toString() + "/normalscorelist.txt");
            filename = "normalscorelist.txt";
        } else {
            path = Paths.get(context.getFilesDir().toString() + "/hardscorelist.txt");
            filename = "hardscorelist.txt";
        }
        scores = new ArrayList<Score>();
        createFile(context.getFilesDir().toString(),filename);
        List<String> lines = Files.readAllLines(path);

        if (!MainActivity.isonline) {
            for (String line : lines) {
//            getUser(line);
                scores.add(getUser(line));
            }
        }
    }

    /**
     * 创建文件夹---之所以要一层层创建，是因为一次性创建多层文件夹可能会失败！
     */
    public static boolean createFileDir(File dirFile) {
        if (dirFile == null) return true;
        if (dirFile.exists()) {
            return true;
        }
        File parentFile = dirFile.getParentFile();
        if (parentFile != null && !parentFile.exists()) {
            //父文件夹不存在，则先创建父文件夹，再创建自身文件夹
            return createFileDir(parentFile) && createFileDir(dirFile);
        } else {
            boolean mkdirs = dirFile.mkdirs();
            boolean isSuccess = mkdirs || dirFile.exists();
            if (!isSuccess) {
                Log.e("FileUtil", "createFileDir fail " + dirFile);
            }
            return isSuccess;
        }
    }


    public static File createFile(String dirPath, String fileName) {
        try {
            File dirFile = new File(dirPath);
            if (!dirFile.exists()) {
                if (!createFileDir(dirFile)) {
                    return null;
                }
            } else if (!dirFile.isDirectory()) {
                boolean delete = dirFile.delete();
                if (delete) {
                    return createFile(dirPath, fileName);
                } else {
                    return null;
                }
            }
            File file = new File(dirPath, fileName);
            if (!file.exists()) {
                if (!file.createNewFile()) {
                    return null;
                }
            }
            return file;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public void getscorelist() throws IOException{
        System.out.println("***********************************************************");
        System.out.println("                         得分排行榜                          ");
        System.out.println("***********************************************************");
        FileInputStream f = new FileInputStream(context.getFilesDir().toString() + "/" + filename);
        InputStreamReader reader = new InputStreamReader(f,"UTF-8");
        StringBuffer sb = new StringBuffer();
        while (reader.ready()) {
            sb.append((char)reader.read());
        }
        System.out.println(sb.toString());
        reader.close();
        f.close();
    }

    @Override
    public void scoreadd(String name, int score) throws IOException {
        Score userscore = new Score(name,score,this.setTime());
        scores.add(userscore);
        Collections.sort(scores);
        OutputStream f = new FileOutputStream(context.getFilesDir().toString() + "/" + filename);
        OutputStreamWriter writer = new OutputStreamWriter(f,"UTF-8");
        for(int i = 0;i < scores.size();i++) {
            scores.get(i).setRank(i + 1);
            writer.append("第" + scores.get(i).getRank() + "名：" + scores.get(i).getUserName() + "," + scores.get(i).getScore() + "," + scores.get(i).getTime());
            writer.append("\r\n");
        }
        writer.close();
        f.close();
    }

    @Override
    public void listclear() throws IOException {
        Files.delete(path);
    }

    @Override
    public void delete(int index) throws IOException {
        System.out.println(index);
        scores.remove(index);
        Collections.sort(scores);
        OutputStream f = new FileOutputStream(context.getFilesDir().toString() + "/" + filename);
        OutputStreamWriter writer = new OutputStreamWriter(f,"UTF-8");
        for(int i = 0;i < scores.size();i++) {
            scores.get(i).setRank(i + 1);
            writer.append("第" + scores.get(i).getRank() + "名：" + scores.get(i).getUserName() + "," + scores.get(i).getScore() + "," + scores.get(i).getTime());
            writer.append("\r\n");
        }
        writer.close();
        f.close();
    }

    public String setTime(){
        Date time = new Date();
        SimpleDateFormat format = new SimpleDateFormat("MM-dd HH:mm:ss");
        String currentTime = format.format(time);
        return currentTime;
    }

    public Score getUser(String line){
        String name = "";
        String time;
        String st1 = "";
        int rank = Integer.parseInt(line.substring(line.indexOf('第') + 1,line.indexOf('名')));
        int i = line.indexOf("：") + 1;
        while (line.charAt(i) != ',') {
            name = name + line.charAt(i);
            i++;
        }
        i++;
        while (line.charAt(i) != ',') {
            st1 = st1 + line.charAt(i);
            i++;
        }
        i++;
        int score = Integer.parseInt(st1);
        time = line.substring(i);
        Score userScore = new Score(rank,name,score,time);
        return userScore;
    }
}
